grid = {}

--set tile size
tilew = 132
tileh = 132

function grid:Load()
  
  print("--setup the grid")

  --grid = {}
  for x = 1,gridSize do
    grid[x] = {}
    for y = 1,gridSize do
      grid[x][y] = 1
    end
  end
  
  --set width and height of table
  grid.w = #grid[1]
  grid.h = #grid

  print("--grid initiated")
    
  --require "selector"
end

function grid:Resize(newSize)
  print("--Resizing grid")
  gridSize = newSize
  for x = 1,gridSize do
    grid[x] = {}
    for y = 1,gridSize do
      grid[x][y] = 1
    end
  end
  print("--Grid resized")
end

function grid:Generate()
  print("--Generating grid")
  for x = 1,gridSize do
    for y = 1,gridSize do
      grid[x][y] = math.random(1,64)
    end
  end
  print("--Grid generated")
end

function grid:Pregrid()
  print("--Generating pregrid")
  for x = 1,gridSize do
    for y = 1,gridSize do
      grid[x][y] = x+y-2
    end
  end
    
end

function grid:draw()
  --for each y
  for ky, _ in ipairs(self) do
    --for each x
    for kx, v in ipairs(self[ky]) do
      --set isometric origin
      local ox = (kx - ky) * tilew/2
      local oy = (kx + ky) * tileh/4
      
      --selector offset
      ox, oy = offset(ox, oy)

      --draw terrains
      grx.draw(tilename[v], ox, oy)
    end
  end  
end

function grid:info()
  if love.keyboard.isDown("tab") then
  --for each y
  for ky, _ in ipairs(self) do
    --for each x
    for kx, v in ipairs(self[ky]) do
      
      --isometric origin
      local ox = (kx - ky) * tilew/2
      local oy = (kx + ky) * tileh/4
      
      --selector offset
      ox, oy = offset(ox, oy)
      
      --set world coordinates
      local x1, x2, x3, x4 = ox + tilew/2, ox + tilew, ox + tilew/2, ox
      local y1, y2, y3, y4 = oy + 30, oy + tileh/4 + 30, oy + tileh/2 +30, oy + tileh/4 +30
      
      grx.setLineWidth(1)
      grx.setColor(0xff,0xff,0xff)
      
      --frame tiles
      grx.quad("line",x1,y1,x2,y2,x3,y3,x4,y4)
      
      --display terrain type and number
      grx.print(v .. "\n" .. kx .. "," .. ky, ox+tilew/4, oy+tileh/8+30)
    end
  end
  end
end


--camera offset
function offset(ox, oy)
  return
    ox + xwidth/2 - selector.draw_x - tilew/2,
    oy + xheight/2 - selector.draw_y - tileh/2
end

